package com.marvels.financial.collection.api.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.marvels.approve.common.dto.EdcSharedDataDTO;
import com.marvels.approve.common.service.SharedDataMqProvideApi;
import com.marvels.common.exception.MarvelsBusinessException;
import com.marvels.common.utils.CommonProperties;
import com.marvels.common.utils.MarvelsLogUtil;
import com.marvels.common.utils.ServerProperties;
import com.marvels.financial.collection.api.CollectionTaskletApi;
import com.marvels.financial.collection.dao.OverdueCollectTaskDao;
import com.marvels.financial.consum.FinancialConsumerExternalApi;
import com.marvels.financial.consum.FinancialConsumerProductApi;
import com.marvels.financial.consum.FinancialConsumerSystemApi;
import com.marvels.financial.loan.dao.McfeCustomerLoanContractDao;
import com.marvels.financial.loan.dto.McfeCustomerLoanContractDTO;
import com.marvels.financial.loan.service.OverDueManageService;

@Service
public class CollectionTaskApiImpl implements CollectionTaskletApi {
	
	@Autowired
	private McfeCustomerLoanContractDao mcfeCustomerLoanContractDao;
	
	@Autowired
	private OverdueCollectTaskDao overdueCollectTaskDao;
	@Autowired
	private FinancialConsumerExternalApi consumerExternalApi;
	@Autowired
	private FinancialConsumerSystemApi consumerSystemApi;
	@Autowired
	private FinancialConsumerProductApi consumerProductApi;
	@Autowired
	private OverDueManageService overDueManageService;
	
	@Autowired
	private SharedDataMqProvideApi sharedDataMqProvideApi;
	
	private static final String END_TD = "</td>";
	
	private static final String START_TD = "<td>";
	@Value("${loanid.prefix}")
	private String loanidPrefix;
	
	@Value("${config.properties.path}")
	private  String configPropertiesPath;
	
	@Transactional(rollbackFor=Exception.class)
	public void process() {
		
		MarvelsLogUtil.getInstance().info(">>>>>>>>>>>>催收定时任务开始");
		String onOff = CommonProperties.getCollectionTask();// 是否开启定时任务
		if (!"on".equalsIgnoreCase(onOff)) {
			MarvelsLogUtil.getInstance().info(">>>>>>>>>>>>催收定时任务未开启");
			return;
		}
		
		// #逾期提醒时间 0还款当天  1逾期
		String overdueRemindersFlag  = ServerProperties.getValue(configPropertiesPath, "common.properties", "overdue.reminders.flag");
		
		
		//1:逾期费用处理
		overDueManageService.OverTenorManage(new Date());
		
		if(StringUtils.isEmpty(overdueRemindersFlag) || "0".equals(overdueRemindersFlag)
				|| ("1".equals(overdueRemindersFlag) && StringUtils.equalsIgnoreCase("Y", CommonProperties.getNewRepaymentFlag()))){
			// 兼容还款当日的入催 add for 2018.12.03 wujf
			try {
				if(StringUtils.equalsIgnoreCase("Y", CommonProperties.getNewRepaymentFlag())) {
					overdueCollectTaskDao.newUpdateContract();
				}else {
					overdueCollectTaskDao.updateContract();
				}
			} catch (Exception e) {
				MarvelsLogUtil.getInstance().error(">>>>>>>>>修改当日还款的合同催收标识异常！",e);
			}
		}
		
		//2.出催，更新update_flag=D，display_flag=N ，对已还款的还款计划出催（条件：逾期天数为0、案件催收更新标识为不等于D、强制入催标识不等于A1）
		try {
			overdueCollectTaskDao.urgent();
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>出入催跑批任务出催异常！",e);
		}
		
		//逾期信息每日记录
		try {
			overdueCollectTaskDao.overdueInformationDailyStatistics();
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>逾期信息每日记录异常！",e);
		}
		
		//3.更新在催案件   更新逾期天数、入催标识、案件催收更新标识、显示标识
		try {
			overdueCollectTaskDao.updateReminder();
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>出入催跑批任务更新再催案件异常！",e);
		}
		
		//4.再次入催 
		try {
			if(StringUtils.equalsIgnoreCase("Y", CommonProperties.getNewRepaymentFlag())) {
				overdueCollectTaskDao.newReminderAgin();
			}else {
				overdueCollectTaskDao.reminderAgin();
			}
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>出入催跑批任务再次入催异常！",e);
		}
		
		//5.首次入催
		try {
			
			if(StringUtils.isEmpty(overdueRemindersFlag) || "0".equals(overdueRemindersFlag)
					|| ("1".equals(overdueRemindersFlag) && StringUtils.equalsIgnoreCase("Y", CommonProperties.getNewRepaymentFlag()))){
				if(StringUtils.equalsIgnoreCase("Y", CommonProperties.getNewRepaymentFlag())) {
					overdueCollectTaskDao.newFirstReminder1();
				}else {
					overdueCollectTaskDao.firstReminder1();
				}
			}else if(StringUtils.isNotEmpty(overdueRemindersFlag) && "1".equals(overdueRemindersFlag)){
				overdueCollectTaskDao.firstReminder2();
			}
			
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>出入催跑批任务首次入催异常！",e);
		}
		
		//6.更新逾期金额
		try {
			if(StringUtils.equalsIgnoreCase("Y", CommonProperties.getNewRepaymentFlag())) {
				overdueCollectTaskDao.newUpdateOverDueAmt();
			}else {
				overdueCollectTaskDao.updateOverDueAmt();
			}
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>出入催跑批任务更新逾期金额异常！",e);
		}
		
		//更新逾期信息每日记录
		try {
			overdueCollectTaskDao.updateOverdueDailyStatistics();
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>更新逾期信息每日记录异常！",e);
		}
		
		
		//查询出逾期信息 将数据推到共享数据平台
		List<McfeCustomerLoanContractDTO> list=mcfeCustomerLoanContractDao.selectOverdueToday();
		MarvelsLogUtil.getInstance().info(">>>>>>>>推送逾期共享数据开始,条数:"+(list==null?0:list.size()));
		if(list!=null && list.size()>0){
			for(McfeCustomerLoanContractDTO dto:list){
				MarvelsLogUtil.getInstance().info(">>>>>>>>推送逾期共享数据loanId:"+dto.getLoanId());
				//循环将逾期数据推给共享平台数据
				EdcSharedDataDTO dataDTO=new EdcSharedDataDTO();
				dataDTO.setCreatedBy("system");
				dataDTO.setCreatedDate(new Date());
				dataDTO.setCustName(dto.getCustName());
				dataDTO.setCustCardNo(dto.getCustCardNo());
				dataDTO.setLoanId(dto.getLoanId());
				dataDTO.setMobileNo(dto.getMobile());
				dataDTO.setSrc(loanidPrefix);
				if(dto.getStatus()==1){//逾期
					dataDTO.setStatus("5");
				}else{
					dataDTO.setStatus("3");
				}
				dataDTO.setUpdatedDate(new Date());
				dataDTO.setUpdatedBy("system");
				try {
					sharedDataMqProvideApi.synSharedData(dataDTO);
				} catch (MarvelsBusinessException e) {
					MarvelsLogUtil.getInstance().error(">>>>>>loanId:"+dto.getLoanId()+",共享数据同步(逾期)异常:",e);
				}
			}
			MarvelsLogUtil.getInstance().info(">>>>>>>>推送逾期共享数据结束");
		}
		//7.发送邮件
//		try {
//			sendNoticeMail();
//		} catch (Exception e) {
//			MarvelsLogUtil.getInstance().error(">>>>>>>>发送邮件异常！",e);
//		}
		
		
	}
}
